package cn.com.gas.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.stereotype.Controller;
import io.swagger.annotations.ApiOperation;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import cn.com.common.constants.Constants;
import cn.com.common.result.DataResult;
import cn.com.gas.constants.GasConstants;
import cn.com.gas.entity.GasFuelchargingEntity;
import cn.com.gas.service.GasFuelchargingService;
import cn.com.system.service.impl.HttpSessionService;
import cn.com.util.TsBqUtils;

/**
 * 油价测算
 *
 * @author shaochangyang
 * @email l2l84o7o5@live.com
 * @date 2024-03-13 23:33:29
 */
@Controller
@RequestMapping("/gas/calculate")
public class GasCalculateController {
	@Autowired
	private GasFuelchargingService gasFuelchargingService;
	@Autowired
	private HttpSessionService httpSessionService;

	/**
	 * 
	 * @param request
	 * @param files
	 * @return
	 */
	@PostMapping("/importDataCalculate")
	@ApiOperation(value = "数据导入并计算")
	@ResponseBody
	public DataResult importDataCalculate(HttpServletRequest request, @RequestParam("file") MultipartFile[] files) {
		String currentUserId = httpSessionService.getCurrentUserId();
		// String currentDeptId = httpSessionService.getCurrentDeptId();
		Date date = new Date();
		List<GasFuelchargingEntity> list = new ArrayList<>();

		List<Double> dieselList = new ArrayList<>(); // 柴油
		List<Double> gasolineList = new ArrayList<>(); // 汽油

		if (files != null && files.length > 0) {
			for (MultipartFile file : files) {
				InputStream inputStream = null;
				try {
					inputStream = file.getInputStream();
		            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
					Sheet sheet = new Sheet(1, 1);
					List<Object> readList = EasyExcelFactory.read(bufferedInputStream, sheet);
					String batch = TsBqUtils.getUUID();
					for (Object object : readList) {
						GasFuelchargingEntity gasFuelchargingEntity = new GasFuelchargingEntity();

						List<String> castList = TsBqUtils.castList(object, String.class);

						String oilDeptName = castList.get(0);// 油站名称
						gasFuelchargingEntity.setOilDeptName(oilDeptName);
						String oilEngineId = castList.get(1);// 油机编号
						gasFuelchargingEntity.setOilEngineId(oilEngineId);
						String oilGunId = castList.get(2);// 油枪编号
						gasFuelchargingEntity.setOilGunId(oilGunId);
						String monitoringId = castList.get(3);// 监控微处理器号
						gasFuelchargingEntity.setMonitoringId(monitoringId);
						String mainboardId = castList.get(4);// 主板内枪号
						gasFuelchargingEntity.setMainboardId(mainboardId);
						String oilProducts = castList.get(5).trim();// 油品
						gasFuelchargingEntity.setOilProducts(oilProducts);
						String oilAmount = castList.get(6);// 油量(升)
						gasFuelchargingEntity.setOilAmount(oilAmount);
						String oilPrice = castList.get(7);// 单价(元/升)
						gasFuelchargingEntity.setOilPrice(oilPrice);
						String money = castList.get(8).trim();// 金额(元)
						gasFuelchargingEntity.setMoney(money);
						String fuelchargingTime = castList.get(9);// 加油时间
						gasFuelchargingEntity.setFuelchargingTime(fuelchargingTime);
						
						gasFuelchargingEntity.setBatch(batch);
						gasFuelchargingEntity.setDeleted(Constants.DATA_NOT_DELETED);
						gasFuelchargingEntity.setCreateTime(date);
						gasFuelchargingEntity.setCreateId(currentUserId);
						
						list.add(gasFuelchargingEntity);
						if (oilProducts.equals(GasConstants.NO_0)) {
							dieselList.add(new Double(money));
						} else if (oilProducts.equals(GasConstants.NO_92) || oilProducts.equals(GasConstants.NO_95)) {
							gasolineList.add(new Double(money));
						}
						
					}

				} catch (Exception e) {
					e.printStackTrace();
					return DataResult.fail("读取文件失败：" + e.toString());
				} finally {
					if (inputStream != null) {
						try {
							inputStream.close();

						} catch (IOException e) {
							e.printStackTrace();
							return DataResult.fail("InputStream流关闭发生异常：" + e.toString());
						}
					}
				}
			}
			
			
			// 异步保存
			new Thread(() -> {
				if (TsBqUtils.isNotNull(list)) {
					gasFuelchargingService.saveBatch(list);
				}
			}).start();
			
			// TODO 开始计算
			List<Double> calculateList = new ArrayList<>();
			Double dieseCalculate = dieseCalculate(dieselList);
			Double gasolineCalculate = gasolineCalculate(gasolineList);
			
			calculateList.add(dieseCalculate);
			calculateList.add(gasolineCalculate);
			
			return DataResult.success(calculateList);

		} else {
			return DataResult.fail("请检查上传的文件!!!");
		}

	}
	
	// 柴油计算
	private static Double dieseCalculate(List<Double> dieselList){
        // 去掉 100以下
		dieselList.removeIf(n -> n < 100);
		if(TsBqUtils.isNotNull(dieselList)){
			Double max = Collections.max(dieselList);
			Double min = Collections.min(dieselList);
			dieselList.remove(Double.valueOf(max));
			dieselList.remove(Double.valueOf(min));
			if(TsBqUtils.isNotNull(dieselList)){
				double asDouble = dieselList.stream().mapToDouble(Double::valueOf).average().getAsDouble();
				return asDouble;
			}else{
				return 0.0;
			}
		}
		return 0.0;
	}
	
	// 汽油计算
	private static Double gasolineCalculate(List<Double> gasolineList){
		// 去掉 100以下
		gasolineList.removeIf(n -> n < 50);
		if(TsBqUtils.isNotNull(gasolineList)){
			
			Double max = Collections.max(gasolineList);
			Double min = Collections.min(gasolineList);
			gasolineList.remove(Double.valueOf(max));
			gasolineList.remove(Double.valueOf(min));
			if(TsBqUtils.isNotNull(gasolineList)){
				double asDouble = gasolineList.stream().mapToDouble(Double::valueOf).average().getAsDouble();
				return asDouble;
			}else{
				return 0.0;
			}
			
		}
		return 0.0;
	}
	
}
